package com.hmdp.service.impl;

import static com.hmdp.utils.RedisConstants.CACHE_NULL_TTL;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

import cn.hutool.bloomfilter.BitMapBloomFilter;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private final BitMapBloomFilter bitMapBloomFilter = new BitMapBloomFilter(1000);

    @Override
    public Shop queryById(Long id) {
        //互斥锁解决缓存击穿
        Shop shop = queryWithMutex(id);
        return shop;
    }

    // 缓存击穿
    private Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //存在，则返回
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, Shop.class);
        }

        //缓存重建
        //获取锁
        String lockKey = "lock:shop:" + id;
        Shop shop;
        try {
            boolean isLocked = tryLock(lockKey);
            // 判断是否获取到锁
            if (!isLocked) {
                //没有获取到
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 获取到
            String s = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(s)) {
                shop = JSONUtil.toBean(s, Shop.class);
                return shop;
            }
            shop = getById(id);
            //模拟延迟
            Thread.sleep(200);
            if (shop == null) {
                //把空值写到redis，防止缓存穿透
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //存在，将查询的数据放到redis中
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            releaseLock(lockKey);
        }
        return shop;
    }

    // //缓存穿透
    public Shop queryWithPassThrough(Long id) {
        // 查询布隆过滤器
        if (!bitMapBloomFilter.contains(String.valueOf(id))) {
            return null;
        }
        // 1.查询缓存
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.缓存命中
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 3.缓存未命中，查询数据库

        Shop shop = getById(id);
        // 更新到布隆过滤器中
        if (ObjectUtil.isNotNull(shop)) {
            bitMapBloomFilter.add(id.toString());
        }
        // 4. 存在，将查询的数据放到redis中
        String jsonStr = JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(key, jsonStr, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    //将数据库查询到的shop放到redisData中并放到redis
    public void saveShopToRedis(Long id,Long expireSeconds){
        //数据库中查询商户
        Shop shop = getById(id);
        //将商户信息和逻辑过期时间封装
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写到redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    private boolean tryLock(String key) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);

    }

    private void releaseLock(String key) {
        stringRedisTemplate.delete(key);

    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺不存在");
        }
        // 更新数据库
        updateById(shop);
        // 删除店铺的redis
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
